<?php
namespace App\Blocks;

use App\Models\Brand;
use App\Models\Carts;
use App\Models\Categories;
use App\Models\Goods;
use App\Models\GoodsImgs;
use DB;
class GoodsBlock
{
    private function _getGoodsListSql($uid, $search=[]){
        $goodsModel         = new Goods();
        $categoriesModel    = new Categories();
        $brandModel         = new Brand();
        $cartModel          = new Carts();

        $perfix = env('DB_PREFIX');

        $sql = DB::table($goodsModel->getTable() . ' as g')
            ->select(
                'g.id',
                'g.c_id',
                'g.b_id',
                'g.show_title',
                'g.name',
                'g.small_image',
                'g.producing_area',
                'g.unit',
                'g.stock_num',
                'g.slogan',
                'g.illustrate',
                'g.sale_num',
                DB::raw("convert(out_price/100, decimal(15,2)) as out_price"),
                DB::raw("convert({$perfix}g.now_price/100, decimal(15,2)) as now_price"),
                'g.status',
                'g.updated_at',
                'c.name as c_name',
                'b.name as b_name',
                DB::raw("if({$perfix}ct.buy_num,{$perfix}ct.buy_num,0) as buy_num")
            )
            ->leftJoin($categoriesModel->getTable() . ' as c', 'c.id', '=', 'g.c_id')
            ->leftJoin($brandModel->getTable() . ' as b', 'b.id', '=', 'g.b_id')
            ->leftJoin($cartModel->getTable() . ' as ct', function ($join) use ($uid){
                $join->on('ct.u_id', DB::raw($uid))
                    ->on('ct.g_id', '=', 'g.id');
            })
            ->whereNull('g.deleted_at')
            ->where('g.status', 1);

        if(isset($search['name'])){
            $sql->where(function ($where) use ($search){
                $where->where('g.name', "%".$search['name']."%")
                    ->orWhere('g.show_title', "%".$search['name']."%");
            });
        }

        if(isset($search['id'])){
            if(is_array($search['id'])){
                $sql->whereIn('g.id', $search['id']);
            }else {
                $sql->where('g.id', $search['id']);
            }
        }

        return $sql;
    }
    public function getGoods($uid, $search=[], $page=1, $pageSize=20){
        $sql = $this->_getGoodsListSql($uid, $search);
        return $sql->orderBy('g.updated_at')
            ->skip(($page - 1) * $pageSize)->take($pageSize)
            ->get();
    }

    public function getGoodsInfo($uid, $id){
        $sql = $this->_getGoodsListSql($uid, ['id' => $id]);
        $info = $sql->first();

        if($info) {
            $info->illustrate = explode('|', $info->illustrate);
            $goodsImgsModel = new GoodsImgs();
            $info->imgs = DB::table($goodsImgsModel->getTable())
                ->where('g_id', $id)
                ->whereNull('deleted_at')
                ->get();
        }

        return $info;

    }
}